<template>
    <div class="container">
      <div class="login-box">
        <div class="title">欢迎登陆</div>
        <div class="content">
          <el-form
            ref="loginFormRef"
            :model="loginForm"
            :rules="loginRules"
            label-width="80px"
            @submit.native.prevent
          >
            <el-col :span="24">
              <el-form-item label="用户名" prop="username">
                <el-input v-model="loginForm.username" clearable placeholder="请输入用户名"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="密码" prop="password">
                <el-input v-model="loginForm.password" type="password" clearable show-password placeholder="请输入密码"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item>
                <el-button style="width: 100%" type="primary" native-type="submit" @click="onLoginSubmit">登&nbsp;陆</el-button>
              </el-form-item>
            </el-col>
          </el-form>
        </div>
      </div>
    </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'

import { ref, onBeforeMount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'

import { login } from '@/api/login/index.js'

const store = useStore()
const route = useRoute()
const router = useRouter()

const loginFormRef = ref()
const loginForm = ref({
  username: '',
  password: '',
  loginType: 0 // 后台登陆
})
const loginRules = ref({
  username: [{required: true, message: '请输入用户名', trigger: 'blur'}],
  password: [{required: true, message: '请输入密码', trigger: 'blur'}],
})

function onLoginSubmit() {
  loginFormRef.value.validate((valid) => {
    if (valid) {
      login(loginForm.value).then(res => {
        if (res && res.code === 200) {
          const token = res.data
          // 1. 将token存入会话存储
          sessionStorage.setItem('authorization', token)
          // 2. 登陆成功，进入首页
          router.replace('/home')
          ElMessage.success(res.message)
        } else {
          ElMessage.error(res.message)
        }
      }).catch(err => {
        console.log('请求失败', err)
      })
    } else {
      return false
    }
  })
}

onBeforeMount(() => {
})
</script>

<style lang="scss" scoped>
.container {
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;

  background-image: url('@/assets/images/login-bg.jpg');
  background-repeat: no-repeat;
  background-size: 100% 100%;
  background-attachment: fixed;

  .login-box {
    padding: 20px;
    width: 450px;
    box-shadow: 2px 2px 5px 0px rgba(50, 50, 50, 0.30);
    background-color: rgba($color: #fff, $alpha: 0.9);
    border-radius: 10px;
    .title {
      text-align: center;
      font-size: 26px;
      font-weight: bold;
      margin-bottom: 20px;
    }
  }
}
</style>